package com.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution08 {
    List<List<Integer>> res = new ArrayList<>();
    boolean[] used;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new boolean[candidates.length];
        Arrays.fill(used, false);
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return res;
    }

    LinkedList<Integer> tmp = new LinkedList<>();
    int sum = 0;

    public void backTracking(int[] candidates, int target, int index) {

        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target) break;
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) continue;
            used[i] = true;
            tmp.add(candidates[i]);
            sum += candidates[i];
            backTracking(candidates, target, i + 1);
            sum -= candidates[i];
            used[i] = false;
            tmp.removeLast();
        }
    }
}
